How to create custom data annotations for custom validation on model property in .Net core?
home / developersection / forums / how to create custom data annotations for custom validation on model property in .net core?
How to create custom data annotations for custom validation on model property in .Net core?
Aryan Kumar
22-Oct-2023In .NET Core, you can create custom data annotations for custom validation on model properties by creating your own custom validation attributes. This allows you to define custom validation rules and apply them to specific properties in your models. Here's how you can create custom data annotations for custom validation:
Step 1: Create a Custom Validation Attribute Class:
You can create a custom validation attribute by inheriting from the ValidationAttribute class and overriding the IsValid method. Here's an example of a custom validation attribute for checking if a string contains a specific keyword:
In this example, the MustContainAttribute checks if a string property contains a specified keyword.
Step 2: Apply the Custom Attribute to a Model Property:
Now, you can apply your custom attribute to a property in your model. For example:
In this case, the Description property is decorated with the MustContain attribute, and it will be validated using the custom validation logic defined in the attribute.
Step 3: Perform Validation in Your Code:
In your application code, you can use the Validator.TryValidateObject method to perform the validation on the model:
The TryValidateObject method checks the Description property using the custom validation attribute and reports any validation errors.
Custom data annotations are powerful tools for creating custom validation rules for your model properties in .NET Core. They allow you to encapsulate validation logic and apply it to specific properties as needed.